//
//  BDHomeUserViewController.m
//  BadBoy
//
//  Created by wen on 2017/3/20.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDHomeUserViewController.h"
#import "BDHomeUserTableViewCell.h"
#import "BDFansViewController.h"
#import "BDHomeModel.h"
#import "BDHomeDetailViewController.h"
#import "BDTextFieldAlert.h"
#import "BDVipPayView.h"
#import "AppDelegate.h"
#import "BDVIPViewController.h"

@interface BDHomeUserViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>
{
    
}
@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIView *customNavi;
@property (nonatomic, strong) UIButton *backButton;

@end

@implementation BDHomeUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    BDUserModel *currentUser = [BDUserModel getCurrentUser];
//    //获取好友列表，获取关注列表
//    if (currentUser.user_id == self.user.user_id) {
//        self.bottomView.hidden = YES;
//    }else {
//        self.bottomView.hidden = NO;
//    }
    
    [self addSubviews];
//    [self requestDetailInfo];
    [self bindRAC];
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.startPage = @"1";
        [self.datasource removeAllObjects];
        [self requestDatasource];
    }];
    [self.tableview.mj_header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    if (self.datasource.count != 0) {
        [self.tableview reloadData];
    }
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)addSubviews{
    [self.view addSubview:self.topView];
    [self.view addSubview:self.customNavi];
    [self.view addSubview:self.backButton];
    [self.view insertSubview:self.tableview atIndex:0];
}

- (void)bindRAC{
    [[self.backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"clickLeftCell"] boolValue] == YES) {
            [[NSUserDefaults standardUserDefaults] setObject:@NO forKey:@"clickLeftCell"];
            [[NSNotificationCenter defaultCenter] postNotificationName:kCloseOrOpenLeft object:nil];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

- (void)requestDatasource{
    NSString *url = [NSString stringWithFormat:@"%@posts?page=%@&size=%@&type=7&user_id=%@", KBDBaseURL, self.startPage,self.pageSize, @(self.user.user_id)];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        NSMutableArray *dataArr = [BDHomeModel mj_objectArrayWithKeyValuesArray:x[@"list"]];
        NSMutableArray *dateArr = [NSMutableArray array];
        for (int i = 0; i < dataArr.count; i++) {
            BDHomeModel *homeModel = dataArr[i];
            NSDate *curDate = [NSDate dateWithTimeIntervalSince1970:homeModel.created_at.floatValue];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"MM-dd"];
            NSString *dateStr = [formatter stringFromDate:curDate];
            if ([dateArr containsObject:dateStr]) {
                homeModel.needDisplayDate = NO;
            }else{
                homeModel.needDisplayDate = YES;
                [dateArr addObject:dateStr];
            }
        }
        [self.datasource addObjectsFromArray:dataArr];
        self.isEnd = [x[@"is_end"] boolValue];
        self.startPage = x[@"next_page"];
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
        self.tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [self requestDatasource];
        }];
        
        [self setTableiewFooterViewStateFor:self.tableview datasourceCount:self.datasource.count];
        [self.tableview reloadData];
        self.tableview.mj_header = nil;
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        // BDLog(ASLocalizedString(@"请求动态出错：%@"), error);
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.topView.bottom = -self.tableview.contentOffset.y;
    self.topView.bottom = self.topView.bottom < 0 ? 0 : self.topView.bottom;
    self.topView.top = self.topView.top > 0 ? 0 : self.topView.top;
    CGFloat offset = scrollView.contentOffset.y;
    CGFloat alpha = 1 + (offset + kBDTopHeight) / 1.0 / (self.topView.height - kBDTopHeight);
    alpha = alpha > 1 ? 1 : alpha;
    alpha = alpha < 0 ? 0 : alpha;
    self.customNavi.alpha = alpha;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDHomeUserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"userCell" forIndexPath:indexPath];
    __weak BDHomeModel *homeModel = self.datasource[indexPath.row];
    [cell configeWithModel:homeModel contentClick:^{
//        if (homeModel.price != 0 && homeModel.isPurchase == NO) {
////            BOOL loca = [BDLocationServer displayFreeOrCharge];
////            BOOL freeKey = [[[NSUserDefaults standardUserDefaults] objectForKey:@"freeKey"] boolValue];
////            BOOL isPhone = [[UIDevice currentDevice].model containsString:@"iPhone"];
//            if ([BDDisplayHelper displayNormalOrFree] == NO) {
//                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"购买会员可以查看所有加密帖子，是否前往购买？")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"取消")otherTitle:@[ASLocalizedString(@"好的")] clickBlock:^(NSInteger index) {
//                    if (index == 1) {
//                        BDVIPViewController *vipVC = [[BDVIPViewController alloc] init];
//                        [self.navigationController pushViewController:vipVC animated:YES];
//                    }
//                }];
//            }else {
//                BDVipPayView *payView = [BDVipPayView showWithProductId:homeModel.my_id type:BDPayTypePost title:ASLocalizedString(@"购买主题")product:[NSString stringWithFormat:ASLocalizedString(@"%@的主题"), homeModel.repost == nil ? homeModel.user.nickname : homeModel.repost.user.nickname] price:[NSString stringWithFormat:ASLocalizedString(@"%@ 元"), @(homeModel.price)] addressArray:nil];
//                __weak AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//                app.payResultBlock = ^(int state) {
//                    // BDLog(ASLocalizedString(@"支付会调用这个回调回到这个页面"));
//                    app.payResultBlock = nil;
//                    [payView hidden];
//                    if (state == 1) {
//                        [MBManager showBriefAlert:ASLocalizedString(@"支付成功")clickHidden:NO clickBlock:nil];
//                        homeModel.purchase = @[@""];
//                        [self.tableview reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//                    }else if (state == 2) {
//                        [MBManager showBriefAlert:ASLocalizedString(@"支付失败")clickHidden:YES clickBlock:nil];
//                    }else if (state == 3) {
//                        [MBManager showBriefAlert:ASLocalizedString(@"支付取消")clickHidden:YES clickBlock:nil];
//                    }
//                    
//                };
//            }
//        }else {
            BDHomeDetailViewController *detailVC = [[BDHomeDetailViewController alloc] init];
            detailVC.homeModel = self.datasource[indexPath.row];
            [self.navigationController pushViewController:detailVC animated:YES];
//        }
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0) {
        cell.cellType = BDHomeUserCellTypeFirst;
        if (self.datasource.count == 1) {
            cell.cellType = BDHomeUserCellTypeFirstAndLast;
        }
    }else if (indexPath.row == self.datasource.count - 1){
        cell.cellType = BDHomeUserCellTypeLast;
    }else{
        cell.cellType = BDHomeUserCellTypeDefault;
    }
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

- (UIView *)topView{
    if (!_topView) {
        self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 240 / 375.0 * kBDScreenWidth)];
        _topView.backgroundColor = [UIColor clearColor];
        UIImageView *bigImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 200)];
        [bigImage sd_setImageWithURL:[NSURL URLWithString:self.user.cover] placeholderImage:[UIImage imageNamed:@"user_top"]];
        bigImage.contentMode = UIViewContentModeScaleAspectFill;
        bigImage.clipsToBounds = YES;
        [_topView addSubview:bigImage];
        
        UIView *blackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 200)];
        blackView.backgroundColor = [UIColor blackColor];
        blackView.alpha = 0.4;
        [_topView addSubview:blackView];
        
        UIImageView *litImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 65, 65)];
        [litImage sd_setImageWithURL:[NSURL URLWithString:self.user.cover] placeholderImage:[UIImage imageNamed:@"avatar"]];
        [_topView addSubview:litImage];
        litImage.right = kBDScreenWidth - 10;
        litImage.centerY = blackView.height - 10;
        litImage.layer.masksToBounds = YES;
        litImage.layer.cornerRadius = litImage.width / 2.0;
        
        _topView.height = litImage.bottom + 10;
        
        UILabel *nickLabel = [[UILabel alloc] init];
        nickLabel.textColor = [UIColor whiteColor];
        nickLabel.font = [UIFont systemFontOfSize:17 weight:1.0];
        nickLabel.text = self.user.nickname;
        nickLabel.width =[nickLabel.text widthWithFont:nickLabel.font];
        nickLabel.height = 25;
        nickLabel.bottom = litImage.centerY;
        nickLabel.right = litImage.left - 10;
        [_topView addSubview:nickLabel];
    }
    return _topView;
}

- (UIView *)customNavi{
    if (!_customNavi) {
        self.customNavi = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, kBDTopHeight)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 24)];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:20];
        label.centerX = _customNavi.width / 2.0;
        label.centerY = 22 + 20;
        label.text = self.user.nickname;
        label.textAlignment = NSTextAlignmentCenter;
        [_customNavi addSubview:label];
        _customNavi.backgroundColor = [UIColor colorWithRed:54/255.0 green:54/255.0 blue:54/255.0 alpha:1.0f];
        _customNavi.alpha = 0;
    }
    return _customNavi;
}

- (UITableView *)tableview{
    if (!_tableview) {
        self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kBDScreenWidth, kBDScreenHeight) style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorColor = [UIColor clearColor];
        _tableview.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        _tableview.contentInset = UIEdgeInsetsMake(self.topView.height, 0, 0, 0);
        _tableview.backgroundColor = [UIColor clearColor];
        [_tableview registerClass:[BDHomeUserTableViewCell class] forCellReuseIdentifier:@"userCell"];
    }
    return _tableview;
}

- (UIButton *)backButton{
    if (!_backButton) {
        self.backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
        _backButton.centerY = 42;
        [_backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    }
    return _backButton;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        self.datasource = [NSMutableArray array];
    }
    return _datasource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
